package activity

import activity.base.BaseActivity
import activity.view.CheckBoxGroup2
import activity.view.CheckBoxGroup3
import activity.view.StatusGroup
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import com.hontech.kdxclient.R
import event.*
import ext.toHexString
import manager.TaskManager
import mvc.model.inventory.GoodsTypeRow
import org.angmarch.views.NiceSpinner
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import protocol.BaseProtocol
import serialport.DeliverPortManager

class SettingActivity : BaseActivity() {
    companion object {
        var isShow = false
        private val NumberList = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
        private val DELIVERY = 0x00
        private val ROW_DELIVERY = 0x01
        private val ALL_DELIVERY = 0x02
    }

    private var rowDeliveryFlag = false // 正在单行出货
    private var allDeliveryFlag = false // 正在全部出货
    private var deliveryFlag = -1 // 出货类型
    private var currentRow = GoodsTypeRow(0, 0) // 当前正在出货的行信息
    private val rows = ArrayList<GoodsTypeRow>(10)

    private val pickGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_pick_normal),
            findViewById(R.id.id_set_pick_locked),
            findViewById(R.id.id_set_pick_time_out)
        )
    }

    private val leftForwardGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_left_forward_normal),
            findViewById(R.id.id_set_left_forward_locked),
            findViewById(R.id.id_set_left_forward_time_out)
        )
    }
    private val rightForwardGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_right_forward_normal),
            findViewById(R.id.id_set_right_forward_locked),
            findViewById(R.id.id_set_right_forward_time_out)
        )
    }
    private val leftPickGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_left_pick_normal),
            findViewById(R.id.id_set_left_pick_locked),
            findViewById(R.id.id_set_left_pick_time_out)
        )
    }
    private val rightPickGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_right_pick_normal),
            findViewById(R.id.id_set_right_pick_locked),
            findViewById(R.id.id_set_right_pick_time_out)
        )
    }
    private val leftRightStepGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_left_right_step_normal),
            findViewById(R.id.id_set_left_right_step_locked),
            findViewById(R.id.id_set_left_right_step_time_out)
        )
    }
    private val upDownStepGroup: CheckBoxGroup3 by lazy {
        CheckBoxGroup3(
            findViewById(R.id.id_set_up_down_step_normal),
            findViewById(R.id.id_set_up_down_step_locked),
            findViewById(R.id.id_set_up_down_step_time_out)
        )
    }
    private val rasterGroup: CheckBoxGroup2 by lazy {
        CheckBoxGroup2(findViewById(R.id.id_set_raster_normal), findViewById(R.id.id_set_raster_error))
    }
    private val statusGroup: StatusGroup by lazy {
        StatusGroup(
            findViewById(R.id.id_set_pick_up_check_box),
            findViewById(R.id.id_set_pick_down_check_box),
            findViewById(R.id.id_set_pick_motor1_forward_check_box),
            findViewById(R.id.id_set_pick_motor1_back_up_check_box),
            findViewById(R.id.id_set_pick_motor2_forward_check_box),
            findViewById(R.id.id_set_pick_motor2_back_up_check_box),
            findViewById(R.id.id_set_left_right_right_check_box),
            findViewById(R.id.id_set_left_right_left_check_box),
            findViewById(R.id.id_set_door_close_check_box),
            findViewById(R.id.id_set_door_key1_check_box),
            findViewById(R.id.id_set_door_key2_check_box),
            findViewById(R.id.id_set_door_key3_check_box),
            findViewById(R.id.id_set_down_key_check_box),
            findViewById(R.id.id_set_up_key_check_box),
            findViewById(R.id.id_set_replenish_key_check_box),
            findViewById(R.id.id_set_up_down_up_check_box),
            findViewById(R.id.id_set_up_down_down_check_box),
            findViewById(R.id.id_set_left_right_zero_check_box)
        )
    }
    private val pickDoorBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_pick_door_check_box_btn)
    }
    private val outlineLedBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_out_line_check_box_btn)
    }
    private val fanBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_fan_check_box_btn)
    }
    private val eLockBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_e_lock_check_box_btn)
    }
    private val heaterBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_heater_check_box_btn)
    }
    private val compressorBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_compressor_check_box_btn)
    }
    private val nucBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_nuc_check_box_btn)
    }
    private val keyLedBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_key_led_check_box_btn)
    }
    private val trayLedBtn: CheckBox by lazy {
        findViewById<CheckBox>(R.id.id_set_tray_led_check_box_btn)
    }
    private val scrollView: ScrollView by lazy {
        findViewById<ScrollView>(R.id.id_set_message_scroll_view)
    }
    private val textViewMessage: TextView by lazy {
        findViewById<TextView>(R.id.id_set_message_text_view)
    }
    private val scrollViewParse: ScrollView by lazy {
        findViewById<ScrollView>(R.id.id_set_message_parse_scroll_view)
    }
    private val textViewMessageParse: TextView by lazy {
        findViewById<TextView>(R.id.id_set_message_parse_text_view)
    }
    private val buttonQueryGoodsType: Button by lazy {
        findViewById<Button>(R.id.id_set_button_goods_type_query)
    }


    private val buttonDelivery: Button by lazy {
        findViewById<Button>(R.id.id_set_button_delivery)
    }
    private val spinnerRow: NiceSpinner by lazy {
        findViewById<NiceSpinner>(R.id.id_set_spinner_row)
    }
    private val spinnerCol: NiceSpinner by lazy {
        findViewById<NiceSpinner>(R.id.id_set_spinner_col)
    }
    private val buttonScan: Button by lazy {
        findViewById<Button>(R.id.id_set_button_scan)
    }
    private val buttonScanReplenish: Button by lazy {
        findViewById<Button>(R.id.id_set_button_scan_replenish)
    }
    private val buttonQuitDebug: Button by lazy {
        findViewById<Button>(R.id.id_set_button_quit_debug)
    }
    private val buttonQuitApplication: Button by lazy {
        findViewById<Button>(R.id.id_set_button_quit_application)
    }
    private val textViewTempValue: TextView by lazy {
        findViewById<TextView>(R.id.id_set_text_view_temp_value)
    }
    private val buttonDeliveryRow: Button by lazy {
        findViewById<Button>(R.id.id_set_button_delivery_row)
    }
    private val buttonDeliveryAll: Button by lazy {
        findViewById<Button>(R.id.id_set_button_delivery_all)
    }
    private val buttonDeliveryPause: Button by lazy {
        findViewById<Button>(R.id.id_set_button_pause)
    }
    private val buttonDeliveryResume: Button by lazy {
        findViewById<Button>(R.id.id_set_button_resume)
    }
    private val buttonSetTemp: Button by lazy {
        findViewById<Button>(R.id.id_set_button_set_temp)
    }
    private val editTextStartTemp: EditText by lazy {
        findViewById<EditText>(R.id.id_set_edit_text_start)
    }
    private val editTextStopTemp: EditText by lazy {
        findViewById<EditText>(R.id.id_set_edit_text_stop)
    }
    private val buttonTestLeftPick: Button by lazy {
        findViewById<Button>(R.id.id_set_button_test_left_pick)
    }
    private val buttonTestLeftRotation: Button by lazy {
        findViewById<Button>(R.id.id_set_button_test_left_rotation)
    }
    private val buttonTestRightPick: Button by lazy {
        findViewById<Button>(R.id.id_set_button_test_right_pick)
    }
    private val buttonTestRightRotation: Button by lazy {
        findViewById<Button>(R.id.id_set_button_test_right_rotation)
    }
    private val buttonInit: Button by lazy {
        findViewById<Button>(R.id.id_set_button_init)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_set)
        pickDoorBtn.setOnCheckedChangeListener(::onClickPick)
        outlineLedBtn.setOnCheckedChangeListener(::onClickOutline)
        fanBtn.setOnCheckedChangeListener(::onClickFan)
        eLockBtn.setOnCheckedChangeListener(::onClickELock)
        heaterBtn.setOnCheckedChangeListener(::onClickHeater)
        compressorBtn.setOnCheckedChangeListener(::onClickCompressor)
        nucBtn.setOnCheckedChangeListener(::onClickNUC)
        keyLedBtn.setOnCheckedChangeListener(::onClickKeyLed)
        trayLedBtn.setOnCheckedChangeListener(::onClickTrayLed)
        buttonDelivery.setOnClickListener(::onClickDelivery)
        buttonScan.setOnClickListener(::onClickScan)
        buttonScanReplenish.setOnClickListener(::onClickReplenish)
        buttonQuitApplication.setOnClickListener(::onClickQuitApplication)
        buttonQuitDebug.setOnClickListener(::onClickQuitDebug)
        buttonQueryGoodsType.setOnClickListener(::onClickQueryGoodsType)
        buttonDeliveryRow.setOnClickListener(::onClickDeliveryRow)
        buttonDeliveryAll.setOnClickListener(::onClickDeliveryAll)
        buttonDeliveryPause.setOnClickListener(::onClickPause)
        buttonDeliveryResume.setOnClickListener(::onClickResume)
        buttonSetTemp.setOnClickListener(::onClickSetTemp)
        buttonInit.setOnClickListener(::onClickInit)
        buttonTestLeftPick.setOnClickListener(::onClickTestLeftPick)
        buttonTestLeftRotation.setOnClickListener(::onClickTestLeftRotation)
        buttonTestRightPick.setOnClickListener(::onClickTestRightPick)
        buttonTestRightRotation.setOnClickListener(::onClickTestRightRotation)

        spinnerRow.attachDataSource(NumberList)
        spinnerCol.attachDataSource(NumberList)

        EventBus.getDefault().register(this)
    }

    override fun onPause() {
        super.onPause()
        isShow = false
    }

    override fun onResume() {
        super.onResume()
        isShow = true
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun onClickTestLeftPick(view: View) {
        val buf = BaseProtocol(0x0F)
            .append7Byte(0x01)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun onClickTestLeftRotation(view: View) {
        val buf = BaseProtocol(0x0F)
            .append7Byte(0x03)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun onClickTestRightPick(view: View) {
        val buf = BaseProtocol(0x0F)
            .append7Byte(0x02)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun onClickTestRightRotation(view: View) {
        val buf = BaseProtocol(0x0F)
            .append7Byte(0x04)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun onClickInit(view: View) {
        val buf = BaseProtocol(0x20).build()
        DeliverPortManager.Instance.write(buf)
    }

    /**
     * 设置温度
     */
    private fun onClickSetTemp(view: View) {
        val tmp1 = editTextStartTemp.text
        if (tmp1.isEmpty()) {
            appendParseMessage("请输入启动温度")
            return
        }
        val tmp2 = editTextStopTemp.text
        if (tmp2.isEmpty()) {
            appendParseMessage("请输入停止温度")
            return
        }
        val start = tmp1.toString().toInt()
        val end = tmp2.toString().toInt()
        if (start <= end) {
            appendParseMessage("启动温度需要比停止温度高")
        }
        val buf = BaseProtocol(0x11)
            .append7Byte(start + 20)
            .append7Byte(end + 20)
            .build()
        DeliverPortManager.Instance.write(buf)
        appendParseMessage("启动温度:$start 停止温度:$end")
    }

    /**
     * 全部出货
     */
    private fun onClickDeliveryAll(view: View) {
        if (rowDeliveryFlag || allDeliveryFlag) {
            Toast.makeText(this, "请先等待出货完成", Toast.LENGTH_SHORT).show()
            appendParseMessage("请先等待出货完成")
            return
        }

        if (rows.isEmpty()) {
            Toast.makeText(this, "请先扫描货道", Toast.LENGTH_SHORT).show()
            appendParseMessage("请先扫描货道")
            return
        }
        deliveryFlag = ALL_DELIVERY
        rowDeliveryFlag = false
        allDeliveryFlag = true
        for (r in rows) {
            if (r.row == 0x01) {
                currentRow = r
                currentRow.lastCol = 1
                onAllDeliveryComplete(1, 0)
                return
            }
        }
    }

    /**
     * 单行出货
     */
    private fun onClickDeliveryRow(view: View) {
        if (rowDeliveryFlag || allDeliveryFlag) {
            Toast.makeText(this, "请先等待出货完成", Toast.LENGTH_SHORT).show()
            appendParseMessage("请先等待出货完成")
            return
        }

        if (rows.isEmpty()) {
            Toast.makeText(this, "请先扫描货道", Toast.LENGTH_SHORT).show()
            appendParseMessage("请先扫描货道")
            return
        }

        val row = spinnerRow.selectedIndex + 1
        for (r in rows) {
            if (r.row == row) {
                currentRow = r
                currentRow.lastCol = 1
                allDeliveryFlag = false
                rowDeliveryFlag = true
                deliveryFlag = ROW_DELIVERY
                onRowDeliveryComplete(0)
                return
            }
        }
        Toast.makeText(this, "没有找到对应的货道", Toast.LENGTH_SHORT).show()
        appendParseMessage("没有找到对应的货道")
    }

    private fun onClickPause(view: View) {
        if (deliveryFlag == DELIVERY) {
            return
        }
        if (deliveryFlag == ROW_DELIVERY) {
            Toast.makeText(this, "单行出货暂停", Toast.LENGTH_SHORT).show()
            appendParseMessage("单行出货暂停")
            rowDeliveryFlag = false
            return
        }
        if (deliveryFlag == ALL_DELIVERY) {
            Toast.makeText(this, "全部出货暂停", Toast.LENGTH_SHORT).show()
            appendParseMessage("全部出货暂停")
            allDeliveryFlag = false
            return
        }
    }

    private fun onClickResume(view: View) {
        if (deliveryFlag == DELIVERY) {
            return
        }
        if (deliveryFlag == ROW_DELIVERY) {
            Toast.makeText(this, "单行出货继续", Toast.LENGTH_SHORT).show()
            rowDeliveryFlag = true
            onRowDeliveryComplete(currentRow.lastCol)
            return
        }
        if (deliveryFlag == ALL_DELIVERY) {
            allDeliveryFlag = true
            Toast.makeText(this, "全部出货继续", Toast.LENGTH_SHORT).show()
            onAllDeliveryComplete(currentRow.row, currentRow.lastCol)
            return
        }
    }

    /**
     * 查询货道
     */
    private fun onClickQueryGoodsType(view: View) {
        val buf = BaseProtocol(0x10).build()
        DeliverPortManager.Instance.write(buf)
        rows.clear()
    }

    /**
     * 单个出货
     */
    private fun onClickDelivery(view: View) {
        if (rowDeliveryFlag || allDeliveryFlag) {
            Toast.makeText(this, "请先等待出货完成", Toast.LENGTH_SHORT).show()
            appendParseMessage("请先等待出货完成")
            return
        }

        val row = spinnerRow.selectedIndex + 1
        val col = spinnerCol.selectedIndex + 1
        val buf = BaseProtocol(0x04)
            .append7Byte(row)
            .append7Byte(col)
            .build()
        DeliverPortManager.Instance.write(buf)
        deliveryFlag = DELIVERY
        allDeliveryFlag = false
        rowDeliveryFlag = false
    }

    /**
     * 货道扫描
     */
    private fun onClickScan(view: View) {
        val buf = BaseProtocol(0x03)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    /**
     * 补货扫描
     */
    private fun onClickReplenish(view: View) {
        val buf = BaseProtocol(0x05)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    /**
     * 取物门
     */
    private fun onClickPick(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x01).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x01).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 示廓灯
     */
    private fun onClickOutline(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x0C).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x0C).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 蒸发器风扇
     */
    private fun onClickFan(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x02).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x02).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 电子锁
     */
    private fun onClickELock(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x07).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x07).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 加热器
     */
    private fun onClickHeater(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x08).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x08).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 压缩机
     */
    private fun onClickCompressor(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x0B).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x0B).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * NUC
     */
    private fun onClickNUC(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x0A).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x0A).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 按键灯
     */
    private fun onClickKeyLed(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x0D).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x0D).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    /**
     * 托盘灯
     */
    private fun onClickTrayLed(buttonView: CompoundButton, isChecked: Boolean) {
        if (isChecked) {
            val buf = BaseProtocol(0x0E).append7Byte(0x00).build()
            DeliverPortManager.Instance.write(buf)
        } else {
            val buf = BaseProtocol(0x0E).append7Byte(0x01).build()
            DeliverPortManager.Instance.write(buf)
        }
    }

    private fun onClickQuitApplication(view: View) {
        val i = Intent(this, MainActivity::class.java)
        i.putExtra(MainActivity.QUIT_ACTION, true)
        startActivity(i)
    }

    private fun onClickQuitDebug(view: View) {
        finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusChangedEvent(env: StatusChangedEvent) {
        pickGroup.setStatus(env.status.pickMotor)
        leftForwardGroup.setStatus(env.status.leftForwardMotor)
        rightForwardGroup.setStatus(env.status.rightForwardMotor)
        leftPickGroup.setStatus(env.status.leftPickMotor)
        rightPickGroup.setStatus(env.status.rightPickMotor)
        leftRightStepGroup.setStatus(env.status.leftRightStepMotor)
        upDownStepGroup.setStatus(env.status.upDownStepMotor)
        rasterGroup.setStatus(env.status.raster)
        statusGroup.setStatus(env.status)
        textViewTempValue.text = String.format("%.1f℃", env.status.tempValueFloat)
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onSerialPortReceiveEvent(env: SerialPortReceiveEvent) {
        appendMessage(env.byteArray.toHexString())
    }

    /**
     * 货道扫描
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onScanResultEvent(env: ScanResultEvent) {
        if (env.isError()) {
            appendParseMessage("扫描故障:" + env.state)
            return
        }
        if (env.isFinish()) {
            appendParseMessage("扫描完成")
            return
        }
        appendParseMessage("扫描结果:${env.row}-${env.col}")
    }

    /**
     * 货物扫描
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryScanResuleEvent(env: DeliveryScanResultEvent) {
        if (env.isError()) {
            appendParseMessage("货物扫描故障:" + env.state)
            return
        }
        if (env.isFinish()) {
            appendParseMessage("货物扫描完成")
            return
        }
        if (env.isNotEmpty()) {
            appendParseMessage("扫描结果:${env.row}-${env.col}=>有货")
            return
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryResultEvent(env: DeliveryResultEvent) {
        appendParseMessage("出货结果:${env.row}-${env.col}=>${env.result()}")
        if (env.isNext()) {
            if (deliveryFlag == ROW_DELIVERY) {
                onRowDeliveryComplete(env.col)
            } else if (deliveryFlag == ALL_DELIVERY) {
                onAllDeliveryComplete(env.row, env.col)
            }
        } else if (env.isError()) {
            deliveryFlag = -1
            rowDeliveryFlag = false
            allDeliveryFlag = false
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onGoodsTypeQueryResultEvent(env: GoodsTypeQueryResultEvent) {
        if (env.isFinish()) {
            appendParseMessage("货道查询完成")
            return
        }
        rows.add(GoodsTypeRow(env.row, env.count))
        appendParseMessage("第${env.row}行有${env.count}列")
    }

    private fun onRowDeliveryComplete(col: Int) {
        currentRow.lastCol = col
        if (!rowDeliveryFlag) { // Pause
            appendParseMessage("第${currentRow.row}行出货暂停")
            return
        }
        val next = col + 1
        if (next > currentRow.count) {
            appendParseMessage("第${currentRow.row}行出货完成")
            allDeliveryFlag = false
            rowDeliveryFlag = false
            deliveryFlag = -1
            return
        }
        appendParseMessage("开始出货:${currentRow.row}-$next")
        val buf = BaseProtocol(0x04)
            .append7Byte(currentRow.row)
            .append7Byte(next)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun onAllDeliveryComplete(row: Int, col: Int) {
        currentRow.lastCol = col
        if (!allDeliveryFlag) { // 暂停
            appendParseMessage("全部出货暂停")
            return
        }
        var nextCol = col + 1
        if (nextCol > currentRow.count) // 下一个需要出货的货道大于本行的货道数量
        {
            val nextRow = row + 1 // 下一行
            var ret = false
            for (r in rows) {
                if (nextRow == r.row) {
                    currentRow = r
                    currentRow.lastCol = 1
                    ret = true
                }
            }
            if (!ret) {
                appendParseMessage("全部出货完成")
                allDeliveryFlag = false
                rowDeliveryFlag = false
                deliveryFlag = -1
                return
            }
            nextCol = 1
        }
        appendParseMessage("开始出货:${currentRow.row}-$nextCol")
        val buf = BaseProtocol(0x04)
            .append7Byte(currentRow.row)
            .append7Byte(nextCol)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun appendMessage(text: String) {
        textViewMessage.append("串口接收:$text \r\n")
        TaskManager.UiHandler.post {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN)
        }
    }

    private fun appendParseMessage(text: String) {
        textViewMessageParse.append("$text \r\n")
        TaskManager.UiHandler.post {
            scrollViewParse.fullScroll(ScrollView.FOCUS_DOWN)
        }
    }
}

